#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
from datetime import date
import os,sys
sys.path.append("../code")

import pandas as pd
from stocksignal import kirogi
from stocksignal import damrey
from tusharedata import update_stock_daily
from tqdm import tqdm
from database import select
from tenacity import retry, stop_after_attempt
from aksharedata import update_etf_basic 
from stocksignal import etf_signal 
from job import *
from aksharedata import update_etf_daily

# 更新ETF日线数据

def update_etf_basic():
    
    etfpath = os.path.join(os.path.expanduser("~"), "stockdate/cvs", "etf_basic.csv")
    df = pd.read_csv(etfpath)
    df = df.rename(columns={'symbol':'code'})
   
    for index, row in df.iterrows():
        log("更新ETF code="+row["code"])
        update_etf_daily(row["code"])
        dfrow = select("etfdaily",("code='%s'" % row["code"]), orderby=["date"])
        cdf = pd.DataFrame(dfrow)
        cdf['date'] = cdf['date'].astype('datetime64[ns]').dt.strftime('%Y%m%d')
        if len(cdf.index)<=0:
            continue
        kirogi.setup(cdf,row["code"],"etf")
        damrey.setup(cdf,row["code"],"etf")
        
 
def log(msg):
    print(msg)


def main():
    try:
        pid = str(os.getpid())
        print("当前进程"+pid)
        job_add(name="更新etf",pid=pid,state=1)
        print ("开始时间 :", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
        # 更新ETF列表
        log("开始更新ETF列表")
        update_etf_basic()
        log("更新ETF列表完成")

        log("开始更新ETF日线数据") 
        update_etf_basic()
        log("更新ETF日线数据完成") 

        log("开始计算 ksignal etf 信号量.") 
        etf_signal()
        log("计算 ksignal etf 信号量完成.")

        print ("结束时间 :", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
        job_update(pid=pid,state=2)

    except Exception as e:
        log("update etf error:"+str(e))
        job_update(pid=pid,state=3)
        sys.exit(-1)

main()